package com.dingreading.cloud.subject.service.impl;

import com.dingreading.cloud.subject.dto.CourseListDto;
import com.dingreading.cloud.subject.entity.Course;
import com.dingreading.cloud.subject.entity.table.CourseTableDef;
import com.dingreading.cloud.subject.mapper.CourseMapper;
import com.dingreading.cloud.subject.service.CourseService;
import com.mybatisflex.core.query.QueryColumn;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryMethods;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.dingreading.cloud.subject.entity.table.CourseVideoTableDef.courseVideo;

/**
 * 服务层实现。
 *
 * @author Administrator
 * @since 2023-11-22
 */
@Service
public class CourseServiceImpl extends BaseServiceImpl<CourseMapper, Course, CourseTableDef> implements CourseService {

    @Override
    protected CourseTableDef getTable() {
        return CourseTableDef.course;
    }


    @Override
    public void updateDownloadNum(Long id) {
        UpdateChain.of(Course.class)
                .set(table.downloadNum, table.downloadNum.add(1))
                .where(table.id.eq(id))
                .update();
    }


    @Override
    public List<CourseListDto> listByTypeIdAndKeyword(Long typeId, String keyword) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.enabled.eq(1));
        if (typeId != null)
            condition.and(table.typeId.eq(typeId));
        if (StringUtils.isNotBlank(keyword))
            condition.and(table.name.like(keyword));

        QueryWrapper videoWrapper = QueryWrapper.create()
                .select(courseVideo.courseId, QueryMethods.count(courseVideo.id).as("cnt"))
                .from(courseVideo)
                .groupBy(courseVideo.courseId);

        QueryColumn videoStatus = QueryMethods.ifNull(QueryMethods.column("b.cnt"), QueryMethods.number(0)).as("videoStatus");
        QueryWrapper wrapper = QueryWrapper.create()
                .select(table.id, table.name, table.url, table.mainTypeName, table.typeName, table.intro,
                        table.orderNum, table.downloadNum, videoStatus
                )
                .from(table).as("a")
                .leftJoin(videoWrapper).as("b").on(table.id.eq(QueryMethods.column("b.course_id")))
                .where(condition)
                .orderBy(table.orderNum.asc());

        return getMapper().selectListByQueryAs(wrapper, CourseListDto.class);
    }

}
